package top.malaoshi.netdisk.service;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.malaoshi.easy.logging.Log;
import top.malaoshi.easy.logging.LogFactory;
import top.malaoshi.jdbc.Record;
import top.malaoshi.jdbc.RecordListUtil;
import top.malaoshi.netdisk.component.RecordListKeyHandler;
import top.malaoshi.netdisk.vo.JsonResult;
import top.malaoshi.netdisk.vo.Note;
import top.malaoshi.netdisk.vo.NoteContent;
import top.malaoshi.sprout.jdbc.DbTemplate;
import top.malaoshi.util.DateTime;
import top.malaoshi.util.id.SnowflakeIdWorker;
import top.malaoshi.util.StringUtil;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class NoteSrvImpl {
    static final Log LOG = LogFactory.getLog(NoteSrvImpl.class);
    @Resource
    private DbTemplate jdbcTemplate;

    @Resource
    private RecordListKeyHandler recordListKeyHandler;
    /**
     * 查询
     * @param keyword
     * @return
     * @throws Exception
     */
    public List<Map> query(String keyword,String typeId) throws Exception {

        String sql = "select tid,n_title from t_note_title where 1 = 1";
        List params = new ArrayList();
        if(keyword!=null && !"".equals(keyword)){
            sql += " and n_title like ? ";
            params.add(keyword + "%");
            params.add("%" + keyword + "%");
        }
        // typeId是1，表示所有
        if(typeId == null || "".equals(typeId) || "1".equals(typeId)){
//            typeId = "1";
//            sql += " and n_type = ? ";
//            params.add(typeId);
        }else{
            sql += " and n_type = ? ";
            params.add(typeId);

        }
        sql += " and n_status ='1' order by modify_time desc";
        List<Record> list = jdbcTemplate.query(sql, params.toArray() );
        List<Map> retList = RecordListUtil.list(list, recordListKeyHandler);
        return retList;

    }
    @Transactional
    public JsonResult showById(String id) throws Exception {

        String titleSQL = "select title.n_title,title.n_type as typeId,type.nt_name as typeName,title.create_time,title.modify_time " +
                "from t_note_title title,t_note_type type " +
                "where title.n_type = type.nt_id " +
                "and title.tid = ? and title.n_status='1' ";
        String contentSQL = "select cid,n_content,n_file,create_time,modify_time from t_note_content where tid = ? and n_status='1' order by modify_time asc ";
        Record ret = null;

        List<Record> list = jdbcTemplate.query(titleSQL, id);
        if (list != null && !list.isEmpty()) {
            ret = list.get(0);
            List<Record> list2 = jdbcTemplate.query(contentSQL, id);
            ret.put("notes",RecordListUtil.list(list2,recordListKeyHandler));
        }

        if(ret == null){
            return JsonResult.fail(110,"没有该笔记！");
        }else {
            Map<String, Object> map = ret.toMap(recordListKeyHandler);
            return JsonResult.success(null,map);
        }

    }
    /**
     * 保存
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public JsonResult save( Note note) throws Exception{
        String title = note.getTitle();
        String typeId = note.getTypeId();
        String content = note.getContent();

        if(title!=null && title.length()>80){
            title = title.substring(0,80);
        }
        Long titleId = SnowflakeIdWorker.getId();
        Long contentId = SnowflakeIdWorker.getId();

        String now = DateTime.now();

        String insertTitle = "insert into t_note_title (tid,n_title,n_status,n_type,create_time,modify_time) values (?,?,1,?,?,?)";
        String insertContent = "insert into t_note_content (cid,tid,n_content,n_status,n_type,create_time,modify_time) values (?,?,?,1,?,?,?)";

        jdbcTemplate.update(insertTitle, titleId, title, typeId, now, now);

        if(!StringUtil.isEmpty(content)) {
            jdbcTemplate.update(insertContent, contentId, titleId, content, typeId, now, now);
        }
        Map map = new HashMap();
        map.put("tid", titleId+"");
        return JsonResult.success("保存成功", map);
    }

    /**
     * 添加一个笔记内容，添加成功后，返回结果
     * @param note
     * @throws Exception
     */
    public Map addContent( Note note) throws Exception{
        String insertContent = "insert into t_note_content (cid,tid,n_content,n_status,n_type,create_time,modify_time) values (?,?,?,1,?,?,?)";

        Long cid = SnowflakeIdWorker.getId();
        String now = DateTime.now();
        int i = jdbcTemplate.update(insertContent,cid, note.getTid(), note.getContent(), note.getTypeId(), now, now);

        Map ret = new HashMap();
        ret.put("cid",cid+"");
        ret.put("create_time",now);
        ret.put("modify_time",now);

        return ret;
    }
    /**
     * 修改标题
     * @param note
     * @throws Exception
     */
    public JsonResult updateTitleById(Note note) throws Exception{
        String tid = note.getTid();
        String title = note.getTitle();

        if(title!=null && title.length()>80){
            return JsonResult.validateFail("标题不能超过80字！");
        }

        String now = DateTime.now();

        String sql = "update t_note_title set n_title = ?,modify_time = ? where tid = ? ";
        jdbcTemplate.update(sql, title,now,tid);
        return JsonResult.success("修改成功！");
    }
    /**
     * 修改内容
     * @param noteContent
     * @throws Exception
     */
    public JsonResult updateContentById(NoteContent noteContent) throws Exception{
        String cid = noteContent.getCid();
        String content = noteContent.getContent();

        String now = DateTime.now();

        String sql = "update t_note_content set n_content = ?,modify_time = ? where cid = ? ";
        jdbcTemplate.update(sql, content,now,cid);
        return JsonResult.success("修改成功！");
    }
    /**
     * 将笔记的标题、全部内容删除到回收站
     * @param id note_title的tid
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public void recycleTitleById(String id) throws Exception {
        jdbcTemplate.setAutoCommit(false);

        String sql = "update t_note_title set n_status = 2 where tid = ? ";
        jdbcTemplate.update(sql, id);
        String sql2 = "update t_note_content set n_status = 2 where tid = ? and n_status = 1";
        jdbcTemplate.update(sql2, id);

    }

    /**
     * 删除到回收站
     * @param id
     * @throws Exception
     */
    public void recycleContentById(String id) throws Exception{

        String sql = "update t_note_content set n_status = 2 where cid = ? ";
        int i = jdbcTemplate.update(sql,id);

    }

    /**
     * 物理删除
     * @param id
     * @throws Exception
     */
    public void deleteById(String id) throws Exception{

        String sql = "delete from t_note where nid = ? ";
        jdbcTemplate.update(sql,id);

    }

    /**
     * 修改分类
     * @param note
     * @return
     * @throws SQLException
     */
    @Transactional(rollbackFor = Exception.class)
    public JsonResult updateTypeById(Note note) throws SQLException {
        String sql1 = "update t_note_title set n_type = ? where tid = ?";
        int n = jdbcTemplate.update(sql1,note.getTypeId(),note.getTid());

        String sql2 = "update t_note_content set n_type = ? where tid = ?";
        n = jdbcTemplate.update(sql2,note.getTypeId(),note.getTid());

        return JsonResult.success("修改成功");
    }

    public Map upload(Note note) throws Exception{
        String insertContent = "insert into t_note_content (cid,tid,n_file,n_status,n_type,create_time,modify_time) values (?,?,?,1,?,?,?)";

        Long cid = SnowflakeIdWorker.getId();
        String now = DateTime.now();
        int i = jdbcTemplate.update(insertContent,cid, note.getTid(), note.getFile(), note.getTypeId(), now, now);

        Map ret = new HashMap();
        ret.put("cid",cid+"");
        ret.put("create_time",now);
        ret.put("modify_time",now);
        LOG.debug("上传文件，添加到数据库中");
        return ret;
    }
}
